package org.example;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;
import org.example.handler.ReadDataHandler;

/**
 * 心跳服务，在TCP长连接中，客户端与服务端定期发送特殊数据包，确保对方可用
 */
public class HeartBeatServer {

    public static void main(String[] args) throws InterruptedException {
        NioEventLoopGroup parent = new NioEventLoopGroup();
        NioEventLoopGroup work = new NioEventLoopGroup();

        ServerBootstrap bootstrap = new ServerBootstrap();

        bootstrap.group(parent, work)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        ChannelPipeline pipeline = socketChannel.pipeline();
                        pipeline.addLast(new StringDecoder(CharsetUtil.UTF_8));
                        pipeline.addLast(new StringEncoder(CharsetUtil.UTF_8));
                        // 5秒没接收到客户端心跳 触发 userEventTriggered
                        // 5 秒没有触发读事件  0秒没触发写事件，0秒没触发读写事件
                        pipeline.addLast(new IdleStateHandler(5, 0, 0));
                        pipeline.addLast(new ReadDataHandler());
                    }
                }).bind(9999).sync().channel().closeFuture().sync();

        parent.shutdownGracefully();
        work.shutdownGracefully();
    }
}
